﻿using System;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace Sapphire.Linq.FieldMaps
{
    internal class FieldMap
    {
        private readonly string _type;
        private readonly string _value;

        public FieldMap(string value)
        {
            _type = "Name";
            _value = value;
        }

        public FieldMap(Guid value)
        {
            _type = "ID";
            _value = value.ToString();
        }

        public XElement GetFieldRef()
        {
            return XElement.Parse(string.Format("<FieldRef {0}=\"{1}\"/>", _type, _value));
        }

        public SPField FindField(SPList list, string propertyName)
        {
            try
            {
                if (_type == "Name" && list.Fields.ContainsField(_value))
                    return list.Fields.GetFieldByInternalName(_value);

                return list.Fields[new Guid(_value)];
            }
            catch (Exception ex)
            {
                throw new ArgumentException("You set incorrect custom mappings", propertyName);
            }
        }
    }
}